<template>
  <div v-if="cacheKey !== undefined && cacheKey !== null && cacheKey !== ''" class="btn-margin-left">
    <el-button
      v-if="showBtn"
      v-hasPermi="btnHasPermi"
      :disabled="isDisable"
      :loading="cacheLoading"
      type="success"
      class="btn-margin-right-load"
      @click="cacheLoad"
    >{{ $t("加载") }}</el-button>
    <el-button
      v-if="showBtn"
      v-hasPermi="btnHasPermi"
      :disabled="isDisable"
      :loading="cacheLoading"
      type="warning"
      class="btn-margin-right-cache"
      @click="cacheData"
    >{{ $t("暂存") }}</el-button>
  </div>
</template>

<script>
import { getSysFormCacheByKey, saveSysFormCache } from '@/api/sys/formCache/sysFormCache'
export default {
  components: { },
  props: {
    isDisable: {
      type: Boolean,
      default: false,
      required: true
    },
    btnHasPermi: {
      type: Array,
      default: () => [],
      required: true
    },
    // 业务数据
    busData: {
      type: Object,
      default: () => {}
    },
    // 缓存键名
    cacheKey: {
      type: String,
      default: undefined,
      required: true
    },
    // 缓存类型. 某个项目或是基金等
    cacheType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      cacheLoading: false,
      showBtn: false
    }
  },
  watch: {
    busData: {
      handler(val) {
        this.showBtn = this.isEmpty(val.id)
      }
    }
  },
  methods: {
    cacheData() {
      var _this = this
      this.$confirm(this.$t('确定后将覆盖您上次的缓存数据, 是否继续?'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        const data = { cacheValue: JSON.stringify(_this.busData), cacheKey: _this.cacheKey, type: _this.cacheType ? _this.cacheType : _this.$route.query.id }
        console.log(data)
        _this.cacheLoading = true
        saveSysFormCache(data).then(() => {
          _this.msgSuccess(_this.$t('缓存成功'))
          _this.cacheLoading = false
        }).catch(err => {
          _this.cacheLoading = false
          _this.msgError(err.message)
        })
      }).catch(() => {
      })
    },
    cacheLoad() {
      this.cacheLoading = true
      getSysFormCacheByKey(this.cacheKey, this.cacheType ? this.cacheType : this.$route.query.id).then(response => {
        console.log(response.data)
        if (response.data !== null) {
          this.$emit('cacheData', JSON.parse(response.data.cacheValue))
        } else {
          this.msgWarning(this.$t('没有缓存数据'))
        }
        this.cacheLoading = false
      }).catch(error => {
        this.cacheLoading = false
        console.log(error)
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .btn-margin-right-load {
    margin: 0 5px 0 0;
  }
  .btn-margin-right-cache {
    margin: 0 10px 0 0;
  }
  .btn-margin-left {
    margin:0 10px
  }
</style>
